/*
* Licensed under the MIT License
* 
* Copyright (c) 2010 Kay Kreuning
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://code.google.com/p/as3hyvesapi
*/
package nl.hyves.api
{
	import flash.net.URLRequest;
	
	import nl.hyves.api.delegates.HyvesCallDelegate;
	import nl.hyves.api.errors.HyvesError;
	import nl.hyves.api.sessions.ISession;
	import nl.hyves.api.sessions.OAuthToken;
	import nl.hyves.api.utils.AuthUtil;
	import nl.hyves.api.utils.TokenStore;

	public class HyvesService
	{
		private const API_ENDPOINT:String = "http://data.hyves-api.nl/";
		
		protected var consumerKey:String;
		protected var consumerSecret:String;
		protected var token:OAuthToken;
		protected var _id:String;
		
		protected var sessionCallback:Function;
		
		/**
		 * Connection status of this service, determined by the status of the current accesstoken.
		 */
		public function get isConnected():Boolean
		{
			return token && token.type == OAuthToken.ACCESSTOKEN;
		}
		
		/**
		 * userId of the current accesstoken, can be null.
		 */
		public function get userId():String
		{
			return token ? token.userId : null;
		}
		
		/**
		 * Methods supported by the current accesstoken can be null.
		 */
		public function get methods():Array
		{
			return token ? token.methods : null;
		}
		
		/**
		 *  Expire date of the current accesstoken, can be null.
		 */
		public function get expireDate():Date
		{
			return token ? token.expireDate : null;
		}
		
		/**
		 * Id of this service, the id is calculated by hashing the consumer key and secret togheter.
		 */
		public function get id():String
		{
			if (!_id)
			{
				_id = AuthUtil.hash(consumerKey + consumerSecret);
			}
			
			return _id;
		}
		
		/**
		 * Construct a new HyvesService instance.
		 * 
		 * @param consumerKey Hyves api consumer key
		 * @param consumerSecret Hyves api consumer secret
		 */
		public function HyvesService(consumerKey:String, consumerSecret:String)
		{
			this.consumerKey = consumerKey;
			this.consumerSecret = consumerSecret;
		}
		
		/**
		 * Connects this service to the Hyves api backend.
		 * 
		 * @param session Session to use when connecting
		 * @param callback Method to call when the connection is successfull or fails
		 */
		public function connect(session:ISession, callback:Function):void
		{
			token = null;
			
			sessionCallback = callback;
			
			session.connect(this, onAccesstoken);
		}
		
		/**
		 * Disconnects this service from the Hyves api backend by disposing the accesstoken.
		 */
		public function disconnect():void
		{
			token = null;
			TokenStore.clear(id);
		}
		
		/**
		 * Call an api method.
		 * 
		 * @param method API method to call
		 * @param callback Method to call with the results or error of the api method call
		 * @param parameters Object with parameters for the specified method 
		 */
		public function call(method:String, callback:Function, parameters:Object = null):void
		{
			parameters ||= new Object();
			
			parameters["ha_method"] = method;
			parameters["ha_version"] = "2.0";
			parameters["ha_format"] = "xml";
			parameters["ha_fancylayout"] = "false";
			parameters["ha_responsecode_always_200"] = "true";
			
			var request:URLRequest = AuthUtil.createRequest(parameters, API_ENDPOINT, consumerKey, consumerSecret, token);
			
			var delegate:HyvesCallDelegate = new HyvesCallDelegate(request, callback);
		}
		
		private function onAccesstoken(token:OAuthToken, error:HyvesError):void
		{
			if (error)
			{
				sessionCallback(null, error);
				return;
			}
			
			this.token = token;
			
			if (isConnected)
			{
				sessionCallback(token, null);
			}
		}
	}
}